from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from .models import Members
from django.views.decorators.csrf import csrf_exempt
from member import models
from django.core import serializers
from django.views.generic import ListView


# Create your views here.

def list_member(request):
    Members.objects.create(members_id='10003', members_name='张小昊', members_phone='1233211234',
                           members_email='xiaohao@zhangtianhao.com')
    member_result = Members.objects.all()
    return render(request, 'members/member_list.html', {'member_result': member_result})


# class MembersListView(ListView):
#     model = Members
#     template_name = 'members/member_list.html'
#     def list(self, request):
#         member_result = Members.objects.all()
#         data = serializers.serialize("xml", member_result)
#         return JsonResponse(data, safe=False)
def memberList(request):
    # id=request.GET['members_id']
    # member_list =Members.objects.filter(members_id=id)
    member_list = Members.objects.all()
    memberJson = []
    for item in member_list:
        member = {'id': item.members_id, 'name': item.members_name, 'phone': item.members_phone,
                  'email': item.members_email}
        memberJson.append(member)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': memberJson}})


@csrf_exempt
def login(request):
    username = request.POST['Username']
    print('user='+username)
    password = request.POST['Password']
    print('pass=' + password)
    user = Members.objects.filter(username=username, password=password)
    if len(user) > 0:
        return JsonResponse({"code": 200, 'message': '登录成功'})
    return JsonResponse({"code": 500, 'message': '登录失败'})